/**
 * Copyright (c) 2011 Technical Centre Radio Systems Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ua.tcrs.tabula.config;

import java.util.Map;
import java.util.ArrayList;

public class MapConfiguration implements Configuration {
	private Map<String,Section> map;
	private MapCreator creator;
	public MapConfiguration( MapCreator creator ) {
		this.creator = creator;
		map = creator.createSectionsMap();
	}
	public Section section( String name ) {
		synchronized ( map ) {
			if ( !map.containsKey(name) ) map.put( name, new MapSection() );
			return map.get(name);
		}
	}
	public Iterable<String> sections() {
		return new ArrayList<String>( map.keySet() );
	}
	
	class MapSection extends Section {
		private Map<String,String> map;
		MapSection() {
			this.map = creator.createEntriesMap();
		}
		@Override
		public Iterable<String> keys() { return new ArrayList<String>( map.keySet() ); }
		@Override
		protected String getInternal( String name ) {
			synchronized ( map ) { return map.get( name ); }
		}
		@Override
		protected void setInternal( String name, String value ) {
			if ( value == null ) {
				synchronized ( map ) { map.remove( name ); }
			} else {
				synchronized ( map ) { map.put( name, value ); }
			}
		}
	}
	
	interface MapCreator {
		Map<String,Section> createSectionsMap();
		Map<String,String> createEntriesMap();
	}
	
}

